package edu.mtu.citizenscience.ethnography;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

import edu.mtu.citizenscience.ethnography.database.Interview;
import edu.mtu.citizenscience.ethnography.database.InterviewDataService;
import edu.mtu.citizenscience.ethnography.database.InterviewPhoto;
import edu.mtu.citizenscience.ethnography.util.DataServiceActivity;
import edu.mtu.citizenscience.ethnography.util.Util;
import edu.mtu.citizenscience.ethnography.util.Util.LocationTriple;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class ImageViewActivity extends DataServiceActivity {

	private static final String LOG_TAG = "ImageViewActivity";
	
	private ImageView image;
	private TextView locationText;
	private TextView dateText;
	
	private int currentInterview;
	private String photoName;
	
	private InterviewPhoto photo;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_view);
		
		image = (ImageView) findViewById(R.id.imageView);
		locationText = (TextView) findViewById(R.id.photoLocation);
		dateText = (TextView) findViewById(R.id.photoDate);
		
		if (savedInstanceState == null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				currentInterview = extras.getInt(Util.ID_KEY, -1);
				photoName = extras.getString(Util.PHOTO_KEY);
			}
		} else {
			currentInterview = savedInstanceState.getInt(Util.ID_KEY);
			photoName = savedInstanceState.getString(Util.PHOTO_KEY);
		}
	}
	
	@Override
	protected void onStop() {
		Log.d(LOG_TAG, "ImageViewActivity is stopping");
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		Log.d(LOG_TAG, "ImageViewActivity is being destroyed");
		super.onDestroy();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(Util.ID_KEY, currentInterview);
		outState.putString(Util.PHOTO_KEY, photoName);
	}
	
	@Override
	protected void performDatabaseOperation() {
		InterviewDataService service = getService();
		
		// Get the width of the display
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		
		Interview i = service.getInterview(currentInterview);
		photo = service.photoFileForInterview(i, photoName);
		
		Bitmap bitmap = Util.decodeSampledBitmapFromFile(
				photo.getPhotoFile().getAbsolutePath(), 
				width, 
				width);

		image.setImageBitmap(bitmap);
		
		Util.formatLocationField(locationText, photo.getLocation());
		DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z", Locale.US);
		dateText.setText(dateFormat.format(photo.getDate()));
	}
	
	public void delete(View view) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.delete_photo_message));
		builder.setPositiveButton(R.string.delete_ok, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					getService().removePhotoFile(photo);
					finish();
				} catch (IOException e) {
					Log.e(LOG_TAG, 
							String.format("Deleting photo threw an exception"), e);
					fail(R.string.io_error);
				}
			}
		});
		builder.setNegativeButton(R.string.cancel, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// Do nothing
				
			}
		});
		builder.create().show();
	}
	
	public void editPhoto(View view) {
		PhotoDialogFragment fragment = new PhotoDialogFragment();
		Bundle args = new Bundle();
		args.putInt(PhotoDialogFragment.ID, currentInterview);
		args.putString(PhotoDialogFragment.NAME, photoName);
		fragment.setArguments(args);
		fragment.show(getSupportFragmentManager(), PhotoDialogFragment.FRAG_TAG);
	}
	
	public static class PhotoDialogFragment extends DialogFragment {
		@SuppressWarnings("hiding")
		private static final String LOG_TAG = "PhotoDialogFragment";
		public static final String FRAG_TAG = LOG_TAG;
		
		private static final String ID = "id";
		private static final String NAME = "filename";
		
		private InterviewPhoto photo;
		
		private EditText sLatDeg;
		private EditText sLatMin;
		private EditText sLatSec;
		
		private EditText sLonDeg;
		private EditText sLonMin;
		private EditText sLonSec;
		
		InterviewDataService service;
		
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			LayoutInflater inflater = getActivity().getLayoutInflater();
			int id = getArguments().getInt(ID, -1);
			String name = getArguments().getString(NAME);
			
			builder.setView(inflater.inflate(R.layout.dialog_photo, null));
			
			service = ((DataServiceActivity)getActivity()).getService();
			Interview i = service.getInterview(id);
			photo = service.photoFileForInterview(i, name);
			
			builder.setPositiveButton(R.string.edit_ok, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					LocationTriple triple;
					String text;
					
					triple = new LocationTriple();
					if (!sLatDeg.getText().toString().equals("") && !sLonDeg.getText().toString().equals("")) {
						Location location = new Location("Editor");
						
						text = sLatDeg.getText().toString();
						triple.degrees = Integer.valueOf(text);
						text = sLatMin.getText().toString();
						if (!text.equals("")) {
							triple.minutes = Integer.valueOf(text);
						} else {
							triple.minutes = 0;
						}
						text = sLatSec.getText().toString();
						if (!text.equals("")) {
							triple.seconds = Double.valueOf(text);
						} else {
							triple.seconds = 0;
						}
						location.setLatitude(triple.doubleValue());
						
						text = sLonDeg.getText().toString();
						triple.degrees = Integer.valueOf(text);
						text = sLonMin.getText().toString();
						if (!text.equals("")) {
							triple.minutes = Integer.valueOf(text);
						} else {
							triple.minutes = 0;
						}
						text = sLonSec.getText().toString();
						if (!text.equals("")) {
							triple.seconds = Double.valueOf(text);
						} else {
							triple.seconds = 0;
						}
						location.setLongitude(triple.doubleValue());
						
						photo.setLocation(location);
						
					} else {
						photo.setLocation(null);
					}
					
					service.savePhotoFile(photo);
				}
			});
			
			builder.setNeutralButton(R.string.edit_cancel, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// Do nothing
				}
			});
			
			AlertDialog dialog = builder.show();
			sLatDeg = (EditText) dialog.findViewById(R.id.sLatDegrees);
			sLatMin = (EditText) dialog.findViewById(R.id.sLatMinutes);
			sLatSec = (EditText) dialog.findViewById(R.id.sLatSeconds);
			sLonDeg = (EditText) dialog.findViewById(R.id.sLonDegrees);
			sLonMin = (EditText) dialog.findViewById(R.id.sLonMinutes);
			sLonSec = (EditText) dialog.findViewById(R.id.sLonSeconds);
			if (photo.getLocation() != null) {
				LocationTriple latitude = new LocationTriple(photo.getLocation().getLatitude());
				sLatDeg.setText(String.valueOf(latitude.degrees));
				sLatMin.setText(String.valueOf(latitude.minutes));
				sLatSec.setText(String.valueOf(latitude.seconds));
				
				LocationTriple longitude = new LocationTriple(photo.getLocation().getLongitude());
				sLonDeg.setText(String.valueOf(longitude.degrees));
				sLonMin.setText(String.valueOf(longitude.minutes));
				sLonSec.setText(String.valueOf(longitude.seconds));
			}
			
			return dialog;
		}
	}

}
